package com.henry.lifegame;

import java.io.*;
import java.util.Scanner;

public class PGM {

    // https://stackoverflow.com/questions/11922252/reading-a-pgm-file-in-java

    public static PGM loadPGMFromFile(String filePath) throws FileNotFoundException {

        try {
            BufferedReader b = new BufferedReader(new FileReader(filePath));
            String magic = b.readLine(); // First line should be 'P2' or 'P5'

            String line = b.readLine(); // Following line contains height and width
            while (line.startsWith("#")) { // Line beginning with "#" is commented out
                line = b.readLine();
            }
            Scanner s = new Scanner(line);

            int width = s.nextInt();
            int height = s.nextInt();

            line = b.readLine(); // Following line contains maxVal
            s = new Scanner(line);

            int maxVal = s.nextInt();

            int[] data = new int[height * width];

            int count = 0;
            int val = 0;

            while (count < height * width && val != -1) {
                val = b.read();
                if (val < 0) break;
                else {
                    if (magic.equals("P5")) { // Binary Format
                        data[count] = val & 0x000000FF;
                        count++;
                    } else if (magic.equals("P2")) { // ASCII format
                        data[count] = val;
                        count++;
                    }
                }
            }
            return new PGM(width, height, data);
        } catch (IOException e) {
            System.out.println(e);
        }
        return null;
    }

    private int[] data;
    private int width;
    private int height;

    PGM(int widthIn, int heightIn, int[] dataIn) {
        this.width = widthIn;
        this.height = heightIn;
        this.data = dataIn;
    }

    public int getWidth() { return width; }
    public int getHeight() { return height; }
    public int[] getData() { return data; }
}
